package org.assistant.csp.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.assistant.common.exception.GetFromDBException;
import org.assistant.common.exception.SaveIntoDBException;
import org.assistant.common.jdbc.core.RowMapper;
import org.assistant.common.jdbc.dao.BasicDao;
import org.assistant.csp.data.Home;
import org.assistant.csp.data.UserSession;

public class UserDaoImpl extends BasicDao implements UserDao {
	protected final Log log = LogFactory.getLog(UserDaoImpl.class);

	private class UserSessionRowMapper implements RowMapper<UserSession> {
		public UserSession mapRow(ResultSet rs, int index) throws SQLException {
			UserSession userSession = new UserSession();
			userSession.setId(rs.getString("user_id_"));
			userSession.setLoginAccount(rs.getString("login_account_"));
			userSession.setName(rs.getString("user_name_"));
			userSession.setEmail(rs.getString("email_"));
			userSession.setRoleId(rs.getLong("role_id_"));
			userSession.setRoleName(rs.getString("role_name_"));
			userSession.setHomeId(rs.getString("home_id_"));
			userSession.setHomeName(rs.getString("home_name_"));
			userSession.setLatestLonginTime(rs.getDate("latest_longin_time_"));
			userSession.setLatestLonginIp(rs.getString("latest_longin_ip_"));

			return userSession;
		}
	}

	/**
	 * 判断登录账号是否在系统中已经存在
	 * 
	 * @param loginAccount
	 * @return
	 * @throws GetFromDBException
	 */
	public boolean isLoginAccountExist(String loginAccount)
			throws GetFromDBException {
		String sql = "select count(*) from common_users where login_account_=?";
		int count = -1;
		try {
			count = getJdbcTemplate().queryForInt(sql, loginAccount);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new GetFromDBException("判断登录账号时出错啦：" + e.getMessage());
		}
		log.debug("count = " + count);
		if (count > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 判断email在系统中是否已经存在
	 * 
	 * @param email
	 * @return
	 * @throws GetFromDBException
	 */
	public boolean isEmailExist(String email) throws GetFromDBException {
		String sql = "select count(*) from common_users where email_=?";
		int count = -1;
		try {
			count = getJdbcTemplate().queryForInt(sql, email);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new GetFromDBException("判断email时出错啦：" + e.getMessage());
		}
		log.debug("count = " + count);
		if (count > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 判断密码是否正确
	 * 
	 * @param loginAccount
	 * @param password
	 * @return
	 * @throws GetFromDBException
	 */
	public boolean isPasswordCorrect(String loginAccount, String password)
			throws GetFromDBException {
		if (password == null) {
			return false;
		}
		String sql = "select passwd_ from common_users where login_account_=?";
		String passwd;
		try {
			passwd = getJdbcTemplate().queryForObject(
				sql, String.class, loginAccount);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new GetFromDBException("判断密码时出错啦：" + e.getMessage());
		}
		if (password.equals(passwd)) {
			return true;
		}
		return false;
	}

	/**
	 * 根据用户账号获取用户信息
	 * 
	 * @param loginAccount
	 * @return
	 * @throws GetFromDBException
	 */
	public UserSession getUserByLoginAccount(String loginAccount)
			throws GetFromDBException {
		StringBuffer getUserSqlBuff = new StringBuffer("select a.user_id_,");
		getUserSqlBuff
			.append("a.login_account_,a.user_name_,a.email_,a.role_id_,");
		getUserSqlBuff.append("c.role_name_,a.home_id_,b.home_name_,");
		getUserSqlBuff.append("a.latest_longin_time_,a.latest_longin_ip_ ");
		getUserSqlBuff.append("from common_users a,common_home b,");
		getUserSqlBuff.append("common_roles c ");
		getUserSqlBuff.append("where a.home_id_=b.home_id_ ");
		getUserSqlBuff.append("and a.role_id_=c.role_id_ ");
		getUserSqlBuff.append("and a.login_account_=?");

		log.debug(getUserSqlBuff.toString());
		log.debug("login_account_=" + loginAccount);

		try {
			return getJdbcTemplate().queryForObject(
				getUserSqlBuff.toString(), new UserSessionRowMapper(),
				loginAccount);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new GetFromDBException("查询用户信息时出错啦：" + e.getMessage());
		}
	}

	/**
	 * 根据用户ID(系统内码)获取用户信息
	 * 
	 * @param userId
	 * @return
	 * @throws GetFromDBException
	 */
	public UserSession getUserByUserId(String userId) throws GetFromDBException {
		StringBuffer getUserSqlBuff = new StringBuffer("select a.user_id_,");
		getUserSqlBuff
			.append("a.login_account_,a.user_name_,a.email_,a.role_id_,");
		getUserSqlBuff.append("c.role_name_,a.home_id_,b.home_name_,");
		getUserSqlBuff.append("a.latest_longin_time_,a.latest_longin_ip_ ");
		getUserSqlBuff.append("from common_users a,common_home b,");
		getUserSqlBuff.append("common_roles c ");
		getUserSqlBuff.append("where a.home_id_=b.home_id_ ");
		getUserSqlBuff.append("and a.role_id_=c.role_id_ ");
		getUserSqlBuff.append("and a.user_id_=?");

		try {
			return getJdbcTemplate().queryForObject(
				getUserSqlBuff.toString(), new UserSessionRowMapper(), userId);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new GetFromDBException("查询用户信息时出错啦：" + e.getMessage());
		}
	}

	/**
	 * 保存用户(注册)信息
	 * 
	 * @param userSession
	 *            -用户Session信息
	 * @param password
	 *            -密码
	 * @param home
	 *            -家庭信息
	 * @return UserSession
	 * @throws SaveIntoDBException
	 * @throws GetFromDBException
	 */
	public UserSession insertUser(UserSession userSession, String password,
			Home home) throws SaveIntoDBException, GetFromDBException {
		StringBuffer sqlBuff = new StringBuffer("insert into common_users(");
		sqlBuff.append("user_id_,login_account_,user_name_,email_,");
		sqlBuff.append("role_id_,home_id_,passwd_,");
		sqlBuff.append("latest_longin_time_,latest_longin_ip_,create_date_) ");
		sqlBuff.append("values(?,?,?,?,?,?,?,now(),'',now())");

		try {
			getJdbcTemplate().update(
				sqlBuff.toString(), userSession.getId(),
				userSession.getLoginAccount(), userSession.getName(),
				userSession.getEmail(), userSession.getRoleId(), home.getId(),
				password);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new SaveIntoDBException("保存用户信息时出错啦：" + e.getMessage());
		}

		return getUserByUserId(userSession.getId());
	}
}
